const axios = require('axios');

(async () => {
  console.log('🔄 用户流程调试测试开始...');
  
  let authToken = null;
  let userId = null;
  let activityId = null;
  
  try {
    // 1. 用户登录
    console.log('\n📝 步骤1: 用户登录');
    const loginResponse = await axios.post('http://localhost:3000/api/auth/login', {
      email: 'alice@student.com',
      password: 'password123'
    });
    
    if (loginResponse.data.token) {
      authToken = loginResponse.data.token;
      userId = loginResponse.data.user.id;
      console.log(`✅ 登录成功 - 用户ID: ${userId}`);
    } else {
      throw new Error('登录失败');
    }
    
    // 2. 获取可参与的活动
    console.log('\n📝 步骤2: 获取可参与的活动');
    const activitiesResponse = await axios.get('http://localhost:3000/api/activities?status=available');
    
    if (activitiesResponse.data.activities.length > 0) {
      activityId = activitiesResponse.data.activities[0].id;
      console.log(`✅ 找到活动 - 活动ID: ${activityId}, 标题: ${activitiesResponse.data.activities[0].title}`);
    } else {
      throw new Error('没有可参与的活动');
    }
    
    // 3. 检查用户当前的参与状态
    console.log('\n📝 步骤3: 检查用户参与状态');
    const activityDetailResponse = await axios.get(`http://localhost:3000/api/activities/${activityId}`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    const currentParticipation = activityDetailResponse.data.activity.userParticipation;
    console.log(`📊 当前参与状态:`, currentParticipation || '未参与');
    
    // 4. 参与活动
    console.log('\n📝 步骤4: 参与活动');
    try {
      const joinResponse = await axios.post(`http://localhost:3000/api/activities/${activityId}/join`, {}, {
        headers: { Authorization: `Bearer ${authToken}` }
      });
      console.log(`✅ 参与活动成功:`, joinResponse.data.message);
    } catch (joinError) {
      if (joinError.response && joinError.response.status === 400) {
        console.log(`⚠️ 参与活动结果:`, joinError.response.data.error);
      } else {
        throw joinError;
      }
    }
    
    // 5. 再次检查参与状态
    console.log('\n📝 步骤5: 确认参与状态');
    const updatedActivityResponse = await axios.get(`http://localhost:3000/api/activities/${activityId}`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    const updatedParticipation = updatedActivityResponse.data.activity.userParticipation;
    console.log(`📊 更新后参与状态:`, updatedParticipation || '仍未参与');
    
    // 6. 尝试签到
    console.log('\n📝 步骤6: 尝试活动签到');
    try {
      const checkinResponse = await axios.post(`http://localhost:3000/api/activities/${activityId}/checkin`, {
        latitude: 39.90420000,
        longitude: 116.40740000
      }, {
        headers: { Authorization: `Bearer ${authToken}` }
      });
      console.log(`✅ 签到成功:`, checkinResponse.data.message);
      console.log(`🎯 勋章状态:`, checkinResponse.data.badgeMessage);
    } catch (checkinError) {
      console.log(`❌ 签到失败:`, checkinError.response?.data?.error || checkinError.message);
      
      // 检查具体的错误原因
      if (checkinError.response?.status === 400) {
        console.log(`📋 可能的原因:`, checkinError.response.data.error);
      }
    }
    
    // 7. 检查用户的勋章
    console.log('\n📝 步骤7: 检查用户勋章');
    const badgesResponse = await axios.get(`http://localhost:3000/api/badges?filter=owned`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log(`🏆 用户拥有的勋章数量:`, badgesResponse.data.badges?.length || 0);
    
    if (badgesResponse.data.badges && badgesResponse.data.badges.length > 0) {
      badgesResponse.data.badges.forEach((badge, index) => {
        console.log(`   勋章 ${index + 1}: ${badge.badge_name || badge.name} (${badge.status})`);
      });
    }
    
    // 8. 检查所有勋章（包括可获得的）
    console.log('\n📝 步骤8: 检查所有勋章');
    const allBadgesResponse = await axios.get('http://localhost:3000/api/badges');
    console.log(`🎖️ 系统中总勋章数量:`, allBadgesResponse.data.badges?.length || 0);
    
    // 9. 检查活动的签到记录
    console.log('\n📝 步骤9: 检查签到记录');
    try {
      // 这里我们需要检查数据库中的签到记录
      console.log(`📋 正在检查活动 ${activityId} 的签到记录...`);
    } catch (error) {
      console.log(`⚠️ 无法直接查询签到记录`);
    }
    
    console.log('\n🎯 调试结果总结:');
    console.log(`- 用户登录: ✅`);
    console.log(`- 活动列表: ✅`);
    console.log(`- 参与状态: ${updatedParticipation ? '✅' : '❌'}`);
    console.log(`- 签到功能: 需要检查具体错误`);
    console.log(`- 勋章数量: ${badgesResponse.data.badges?.length || 0}`);
    
  } catch (error) {
    console.error('❌ 调试过程中出现错误:', error.message);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应数据:', error.response.data);
    }
  }
})(); 